package com.hl.godsent.view

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.webkit.SslErrorHandler
import android.webkit.ValueCallback
import android.webkit.WebMessagePort
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.AppUtils
import com.hl.godsent.GodSent
import com.hl.godsent.Interface.IDownloadListener
import com.hl.godsent.R
import com.hl.godsent.utils.CoreLog
import com.hl.godsent.utils.CustomWebViewChrome
import com.hl.godsent.utils.DownloadUtil
import com.hl.godsent.utils.JavaScriptObject
import com.hl.godsent.utils.Permission
import java.io.File


class MainActivity : AppCompatActivity() {
    lateinit var webView: WebView
    var i = 0;
    var mUploadCallbackAboveL: ValueCallback<Array<Uri>>? = null
    var mUploadCallbackBelow: ValueCallback<Uri>? = null
    private lateinit var imageUri: Uri
    private var REQUEST_CODE = 1234
    lateinit var customWebViewChrome: CustomWebViewChrome
    private lateinit var port: WebMessagePort



    @RequiresApi(Build.VERSION_CODES.O)
    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        customWebViewChrome = CustomWebViewChrome(this@MainActivity)
        setContentView(R.layout.activity_main)


        // 获得vebview控件
        webView = findViewById<WebView>(R.id.hl_webView)

        supportActionBar?.setDisplayHomeAsUpEnabled(false)

        //声明WebSettings子类
        val webSettings = webView.settings
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.javaScriptEnabled = true  //设置js可以直接打开窗口，如window.open()，默认为false

        //设置自适应屏幕，两者合用
        webSettings.useWideViewPort = true //将图片调整到适合webview的大小
        webSettings.loadWithOverviewMode = true // 缩放至屏幕的大小
        webSettings.javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口
        webSettings.domStorageEnabled = true


        //是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        webSettings.setSupportZoom(true)
        //是否可以缩放，默认true
        webSettings.builtInZoomControls = false
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE

        val appCachePath = applicationContext.cacheDir.absolutePath
        webSettings.allowFileAccess = true
        webSettings.allowContentAccess = true

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            webSettings.safeBrowsingEnabled = true
        }
        webSettings.mediaPlaybackRequiresUserGesture = false


        webView.addJavascriptInterface(JavaScriptObject(this@MainActivity), "HLJsBridge")

        webView.loadUrl("http://10.30.5.2:8087/m/")
        //系统默认会通过手机浏览器打开网页，为了能够直接通过WebView显示网页，则必须设置
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                if (request != null) {
                    CoreLog.i("webview刷新", "${request.url}")
                }
                return false
            }

            @SuppressLint("WebViewClientOnReceivedSslError")
            override fun onReceivedSslError(
                view: WebView?,
                handler: SslErrorHandler,
                error: SslError?
            ) {
                super.onReceivedSslError(view, handler, error)
                handler.proceed()
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
//                initPort()
//                showUpdateDialog("我看看看看", "https://file-storage.hailiangedu.com/static-tchsys/android/app-release.apk")
            }
        }

        webView.webChromeClient = customWebViewChrome
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        customWebViewChrome.onActivityResult(requestCode, resultCode, data)
        Log.i("TAG", "🔥   $requestCode, $resultCode, $data")
    }

    override fun onStart() {
        super.onStart()
        Permission.checkPermission(this)
    }

    override fun onResume() {
        super.onResume()
        if (Permission.isPermissionGranted(this)) {
            Log.i("PERMISSION", "请求权限成功")
        }
    }
    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String?>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == Permission.REQUEST_CODE) {
            for (grantResult in grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    Log.e("Permission", "授权失败！")
                    // 授权失败，退出应用
//                    finish()
                    return
                }
            }
        }
    }
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0) {
            false
        } else super.onKeyDown(keyCode, event)
    }


    private fun showUpdateDialog (desc: String, url: String) {
        Log.e("🍉", "running")
        Log.e("🍉", "$this")
        val updateDialog: AlertDialog
        val updateView = LayoutInflater.from(this@MainActivity).inflate(R.layout.dialog_update, null, false)
        updateDialog = AlertDialog.Builder(this@MainActivity).setView(updateView).create()
        updateView.findViewById<TextView>(R.id.update_version_info).text = desc
        updateView.findViewById<TextView>(R.id.update_version_info).text = desc
        val mProgressBar: ProgressBar = updateView.findViewById(R.id.id_progress)
//        点击空白处不消失
        updateDialog?.setCanceledOnTouchOutside(false)
        updateDialog?.setCancelable(false)
        val updateBtn = updateView.findViewById<Button>(R.id.dialog_update_button)
        updateBtn.setOnClickListener {
//            updateDialog?.dismiss()
            DownloadUtil().download(GodSent.getGodSentContext(), url, object: IDownloadListener {
                override fun onDownloadSuccess(file: File) {
                    Log.i("TAG", "file: $file")
                    AppUtils.installApp(file)
                }

                override fun onDownloading(progress: Int) {
                    Log.i("TAG", "进度: $progress")
                    mProgressBar.progress = progress
                }

                override fun onDownloadFailed() {
                    Log.i("TAG", "失败")
                }
            })
        }
        updateDialog?.setCanceledOnTouchOutside(false)
        updateDialog?.window?.setBackgroundDrawableResource(R.drawable.shap_radius_forty)
        updateDialog?.show()
        updateDialog?.window?.setLayout(640, LinearLayout.LayoutParams.WRAP_CONTENT)
    }

}

